package com.nce.web;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springside.modules.orm.Page;
import org.springside.modules.orm.PropertyFilter;
import org.springside.modules.utils.web.struts2.Struts2Utils;

import com.nce.entity.Msg;
import com.nce.entity.MsgStats;
import com.nce.entity.Vp;
import com.nce.entity.Words;
import com.nce.service.MsgService;
import com.nce.service.WordsService;
import com.nce.util.MsgParser;
import com.opensymphony.xwork2.ActionSupport;

@Namespace("/admin")
@Results({ @Result(name = CrudActionSupport.RELOAD, location = "msg.action", type = "redirect") })
public class MsgAction extends ActionSupport {
	
	@Autowired
	private MsgService msgService;
	
	@Autowired
	private WordsService wordsService;
	
	private Date sdate ;
	private Date edate;
	private String qqid;
	private String username;
	private String content;
	private String qqgroup;
	private Integer wordCounts;
	private String minwords;
	private String maxwords;
	private String sdateStr;
	private String edateStr;
	private String vpstats;
	private String allwords;
	
	Page<Msg> page = new Page<Msg>(20);

	private static final long serialVersionUID = -6999904901932084228L;
	private static Logger logger = LoggerFactory.getLogger(MsgAction.class);

	
	public String importMsg() {		
		String filepath = Struts2Utils.getParameter("filepath");		
		
		if(filepath==null){
			Struts2Utils.getRequest().setAttribute("msg", "文件路径错误");
		}
		
		MsgParser parser = new MsgParser();
		try {
			List<Msg> msgList = parser.parseMsg(filepath,sdate,edate);
			int total = msgList.size();
//			int limitValue = 10000;
//			int totalValue = msgList.size();
//			while(totalValue > limitValue){
//				List<Msg> tmpMsgList = msgList.subList(0, limitValue);
//				msgService.saveMsgList(tmpMsgList);
//				msgList = msgList.subList(limitValue, totalValue);	
//				totalValue = msgList.size();
//			}
			msgService.saveMsgList(msgList);

			
			Struts2Utils.getRequest().setAttribute("msg", "数据成功导入共: "+total+"条");
			logger.warn("数据成功导入共: "+total+"条,文件:"+filepath);
		} catch (Exception e) {			
			Struts2Utils.getRequest().setAttribute("msg", "导入数据出错,文件路径为:["+filepath+"],更多消息:"+e.getMessage());
			logger.error("导入数据出错,文件路径为:["+filepath+"]",e);
		}		
		
		return "goimport";
	}
	
	public String list(){
		
		if(allwords!=null && allwords.equals("1")){//选中所有敏感词直接数据库中读取
			List<Words> wordsList = wordsService.getAllWords();
			StringBuilder  newContent = new StringBuilder();
			if(wordsList!=null){
				for(Words words:wordsList){
					newContent.append(words.getWords()).append(" ");
				}
				System.out.println(newContent.toString());
				this.content = newContent.toString();
			}
		}
		boolean isOr = true;//(allwords!=null && allwords.equals("1"));
		if(vpstats==null || vpstats.equals("0")){

		
			page = msgService.findPageMsgWithoutVp(qqid,sdateStr, edateStr, minwords, maxwords, qqgroup, username, content, page,isOr);
			
		}else if(vpstats.equals("1")){
			
			
			page = msgService.findPageMsgWithVp(qqid,sdateStr, edateStr, minwords, maxwords, qqgroup, username, content, page,isOr);
			
		}
		

		//content是搜索字符串,msg.getContent是真正的内容
		if(StringUtils.isNotEmpty(content)){
			for(Msg msg:page.getResult()){
				String newContent = lightContent(msg.getContent(),content);
				msg.setLightContent(newContent);
			}
		}
		

		return "msg";
	}
	
	/**
	 * 把内容按搜索词进行高亮处理
	 * @param content
	 * @param words
	 * @return
	 */
	private String lightContent(String content,String words) {
		String [] wordArr = words.split(" ");
		for(String word:wordArr){
			content = content.replace(word, "<span style='color:#CD4F39;'>" + word + "</span>");
		}
		return content;
	}

	public String exportOld(){
		
		if(allwords!=null && allwords.equals("1")){//选中所有敏感词直接数据库中读取
			List<Words> wordsList = wordsService.getAllWords();
			StringBuilder  newContent = new StringBuilder();
			if(wordsList!=null){
				for(Words words:wordsList){
					newContent.append(words.getWords()).append(" ");
				}
				System.out.println(newContent.toString());
				this.content = newContent.toString();
			}
		}
		boolean isOr = true;//(allwords!=null && allwords.equals("1"));
		
		//内容并操作
		List<PropertyFilter> filters = initFilters();	
		List<Msg> msgList = null;
		
		if(vpstats==null || vpstats.equals("0")){

			//msgList = msgService.findMsgList(filters);
			msgList = msgService.findMsgListWithoutVp(qqid,sdateStr, edateStr, minwords, maxwords, qqgroup, username, content, page,isOr);
			
		}else if(vpstats.equals("1")){
			msgList = msgService.findMsgListWithVp(qqid,sdateStr, edateStr, minwords, maxwords, qqgroup, username, content, page,isOr);
		}
		
		
		if(msgList!=null && msgList.size() > 0){
			String abc = Struts2Utils.getRequest().getRealPath("/down/");
			Format formatter = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss");
		    String dateStr = formatter.format(new Date());
		    String downUrl = "http://127.0.0.1/down/"+dateStr+"_msg.dam";
		    	BufferedWriter out = null;
				try {
			        out = new BufferedWriter(new FileWriter(abc+"/"+dateStr+"_msg.dam"));
//			        out.write(Msg.formatToCsvHeader());
			        int i = 1;
			        for(Msg msg : msgList){
			        	if(vpstats==null || vpstats.equals("0")){

			        		out.write(msg.formatToTxt(i));
			    			
			    		}else if(vpstats.equals("1")){
			    			out.write(msg.formatToTxtWithVp(i));
			    		}
			        	
			        	i++;
			        	out.flush();
			        }		        
			        
			    } catch (IOException e) {
			    	logger.error("导出消息文件出错",e);
			    }finally{
			    	if(out!=null){
			    		try {
							out.close();
						} catch (IOException e) {
							logger.error("导出消息文件出错",e);
						}
			    	}
			    }
			    
			    try {
					Struts2Utils.getResponse().sendRedirect(downUrl);
				} catch (IOException e) {					
					logger.error("导出消息文件出错",e);
				}    
		}	
		return null;
	}
	
public String export(){
		
		List<Msg> msgList = null;
		boolean isOr = true;
		String abc = Struts2Utils.getRequest().getRealPath("/down/");
		Format formatter = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss");
		String dateStr = formatter.format(new Date());
		String downUrl = "http://127.0.0.1/down/" + dateStr + "_msg.dam";
		BufferedWriter out = null;
		try {
			out = new BufferedWriter(new FileWriter(abc + "/" + dateStr + "_msg.dam"));
			
			String [] wordsArr = content.split(" ");
			
			
			if (allwords != null && allwords.equals("1")) {// 选中所有敏感词直接数据库中读取
				List<Words> wordsList = wordsService.getAllWords();
				wordsArr = new String[wordsList.size()];
				for(int k= 0 ; k < wordsArr.length; k++){
					wordsArr[k]=(wordsList.get(k)).getWords();
				}
			} else {
				wordsArr = content.split(" ");
			}

				if (wordsArr != null&&wordsArr.length > 0) {
					for (String words : wordsArr) {
						if (vpstats == null || vpstats.equals("0")) {

							msgList = msgService.findMsgListWithoutVp(qqid, sdateStr, edateStr, minwords, maxwords,
									qqgroup, username, words, page, isOr);

						} else if (vpstats.equals("1")) {
							msgList = msgService.findMsgListWithVp(qqid, sdateStr, edateStr, minwords, maxwords,
									qqgroup, username, words, page, isOr);
						}

						int i = 1;
						out.write("========================\n");
						out.write(words+"\n");
						out.write("========================\n");
						out.flush();
						for (Msg msg : msgList) {
							if (vpstats == null || vpstats.equals("0")) {
								
								String ncontent = msg.formatToTxt(i).replace(words, "[[**" + words + "**]]");
								out.write(ncontent);

							} else if (vpstats.equals("1")) {
								String ncontent = msg.formatToTxtWithVp(i).replace(words, "[[**" + words + "**]]");
								out.write(ncontent);
							}

							i++;
							out.flush();
						}
						
						out.write(words+"结束=======================\n");
						out.flush();
					}

				}
			
		} catch (IOException e) {
			logger.error("导出消息文件出错", e);
		} finally {
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					logger.error("导出消息文件出错", e);
				}
			}
		}

		try {
			Struts2Utils.getResponse().sendRedirect(downUrl);
		} catch (IOException e) {
			logger.error("导出消息文件出错", e);
		}

		return null;
	}
	
	public String index(){			
		return "msg";
	}
	
	public String cleanMsg(){
		String sd = Struts2Utils.getParameter("sd");
		String ed = Struts2Utils.getParameter("ed");
		if(sd==null && ed ==null){
			msgService.dleteAllMsg();
			addActionMessage( "所有消息数据已经被清除.");
		}else{
			msgService.deleteMsgByDate(sd,ed);
			System.out.println(sd+ "        "+ed);
		}
		
		return "goimport";
		
	}
	
	private List<PropertyFilter> initFilters() {
		List<PropertyFilter> filters = PropertyFilter.buildFromHttpRequest(Struts2Utils.getRequest());
		if (StringUtils.isNotEmpty(qqid)) {
			PropertyFilter pf = new PropertyFilter("EQS_qqid", qqid);
			filters.add(pf);
		}
		
		if (StringUtils.isNotEmpty(qqgroup)) {
			PropertyFilter pf = new PropertyFilter("EQS_qqgroup", qqgroup);
			filters.add(pf);
		}
		
		if (StringUtils.isNotEmpty(username)) {
			PropertyFilter pf = new PropertyFilter("LIKES_username", username);
			filters.add(pf);
		}		
		
		//搜索多个词用空格分开
		if (StringUtils.isNotEmpty(content)) {
			String [] words = content.split(" ");
			for(String word :words){
				if(StringUtils.isNotEmpty(word)){
					PropertyFilter pf = new PropertyFilter("LIKES_content", word);
					filters.add(pf);
				}
			}
		}
		
		if (StringUtils.isNotEmpty(maxwords)) {
			PropertyFilter pf = new PropertyFilter("LEI_maxwords", maxwords);
			filters.add(pf);
		}
		
		if (StringUtils.isNotEmpty(minwords)) {
			PropertyFilter pf = new PropertyFilter("GEI_wordCounts", minwords);
			filters.add(pf);
		}
		
		if (StringUtils.isNotEmpty(maxwords)) {
			PropertyFilter pf = new PropertyFilter("LEI_maxwords", maxwords);
			filters.add(pf);
		}
		
		if (StringUtils.isNotEmpty(minwords)) {
			PropertyFilter pf = new PropertyFilter("GEI_wordCounts", minwords);
			filters.add(pf);
		}
		
		if (StringUtils.isNotEmpty(edateStr)) {
			PropertyFilter pf = new PropertyFilter("LED_ctime", edateStr);
			filters.add(pf);
		}
		
		if (StringUtils.isNotEmpty(sdateStr)) {
			PropertyFilter pf = new PropertyFilter("GED_ctime", sdateStr);
			filters.add(pf);
		}

		return filters;
	}


	public Date getSdate() {
		return sdate;
	}


	public void setSdate(Date sdate) {
		this.sdate = sdate;
	}


	public Date getEdate() {
		return edate;
	}


	public void setEdate(Date edate) {
		this.edate = edate;
	}

	public String getQqid() {
		return qqid;
	}

	public void setQqid(String qqid) {
		this.qqid = qqid;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getContent() {
		return content;
	}

	public void setContent(String content) {
		this.content = content;
	}

	public String getQqgroup() {
		return qqgroup;
	}

	public void setQqgroup(String qqgroup) {
		this.qqgroup = qqgroup;
	}

	public Integer getWordCounts() {
		return wordCounts;
	}

	public void setWordCounts(Integer wordCounts) {
		this.wordCounts = wordCounts;
	}

	public String getMinwords() {
		return minwords;
	}

	public void setMinwords(String minwords) {
		this.minwords = minwords;
	}

	public String getMaxwords() {
		return maxwords;
	}

	public void setMaxwords(String maxwords) {
		this.maxwords = maxwords;
	}

	public String getSdateStr() {
		return sdateStr;
	}

	public void setSdateStr(String sdateStr) {
		this.sdateStr = sdateStr;
	}

	public String getEdateStr() {
		return edateStr;
	}

	public void setEdateStr(String edateStr) {
		this.edateStr = edateStr;
	}

	public Page<Msg> getPage() {
		return page;
	}

	public void setPage(Page<Msg> page) {
		this.page = page;
	}

	public String getVpstats() {
		return vpstats;
	}

	public void setVpstats(String vpstats) {
		this.vpstats = vpstats;
	}

	public String getAllwords() {
		return allwords;
	}

	public void setAllwords(String allwords) {
		this.allwords = allwords;
	}

	

	public WordsService getWordsService() {
		return wordsService;
	}

	public void setWordsService(WordsService wordsService) {
		this.wordsService = wordsService;
	}
	
}